package com.example.uniapp.activity.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.example.uniapp.R;
import com.example.uniapp.activity.main.CookbookShowActivity;
import com.example.uniapp.bean.CookbookBean;

import java.util.List;

/**
 * 用于显示home界面的食谱的adapter
 */
public class HomeCookbookListAdapter extends ArrayAdapter<CookbookBean>{

    private List<CookbookBean> cookbookBeanList;
    private Context context;

    public HomeCookbookListAdapter(@NonNull Context context, List<CookbookBean> list) {
        super(context, R.layout.list_user_cookbook_list, list);
        this.context = context;
        this.cookbookBeanList = list;
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, @NonNull ViewGroup viewGroup) {
        //获取主界面
        if(convertView == null) {
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.list_user_cookbook_list, viewGroup, false);
        }

        //设置展示的内容
        CookbookBean temp = cookbookBeanList.get(position);

        //先获取各个view
        ImageView userCookbookListImg = convertView.findViewById(R.id.user_cookbook_list_img);
        TextView userCookbookListName = convertView.findViewById(R.id.user_cookbook_list_name);
        TextView userCookbookListUser = convertView.findViewById(R.id.user_cookbook_list_user);

        //设置view的内容
        Bitmap bitmap = BitmapFactory.decodeFile(temp.getCookbookImg());
        userCookbookListImg.setImageBitmap(bitmap);
        userCookbookListName.setText(temp.getCookbookName());
        userCookbookListUser.setText(temp.getUserId());

        //设置当点击某个食谱时的效果
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //保存点击的食谱的信息并跳转到查看食谱信息界面
                Intent intent = new Intent(getContext(), CookbookShowActivity.class);
                intent.putExtra("cookbook", temp);
                getContext().startActivity(intent);
            }
        });
        return convertView;
    }
}
